package cn.com.basic.framework.aliyun.oss.upload;

import cn.com.basic.framework.aliyun.oss.OSSManager;
import cn.hutool.core.lang.Assert;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.AppendObjectResult;
import com.aliyun.oss.model.ObjectMetadata;

import java.io.ByteArrayInputStream;
import java.io.File;

/**
 * 追加类型的文件（Append Object）暂时不支持copyObject操作
 * <p>
 * 适合视频文件和日志文件这样需要时常更新追加的场景
 *
 * @author zhuxj
 */
public class AppendUploader extends Uploader {
    public AppendUploader(OSSManager ossManager) {
        super(ossManager);
    }

    /**
     * 追加上传字符串内容
     *
     * @param bucketName   目标存储空间
     * @param objName      目标文件名称
     * @param content      字符串内容
     * @param filePosition 追加起始点，一般是文件的长度
     * @return {@link AppendObjectResult} 通过{@link AppendObjectResult#getNextPosition()}来获得追加的点位
     */
    public AppendObjectResult appendUpload(String bucketName, String objName, String content, long filePosition) {

        Assert.isTrue(this.ossManager.getOss() != null, "oss client cannot be null");

        if (filePosition < 0) {
            filePosition = 0;
        }
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("text/plain");

        AppendObjectRequest request = new AppendObjectRequest(bucketName, objName, new ByteArrayInputStream(content.getBytes()), metadata);

        request.setPosition(filePosition);

        return this.ossManager.getOss().appendObject(request);
    }

    /**
     * 追加上传文件内容
     *
     * @param bucketName   目标存储空间
     * @param objName      目标文件名称
     * @param file         待上传文件
     * @param filePosition 追加起始点，一般是文件的长度
     * @return {@link AppendObjectResult} 通过{@link AppendObjectResult#getNextPosition()}来获得追加的点位
     */
    public AppendObjectResult appendUpload(String bucketName, String objName, File file, long filePosition) {

        Assert.isTrue(this.ossManager.getOss() != null, "oss client cannot be null");

        if (filePosition < 0) {
            filePosition = 0;
        }
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("text/plain");

        AppendObjectRequest request = new AppendObjectRequest(bucketName, objName, file, metadata);

        request.setPosition(filePosition);

        return this.ossManager.getOss().appendObject(request);
    }


}
